package com.ruoyi.datastatistics.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.Month;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.stereotype.Service;
import com.ruoyi.datastatistics.mapper.CopyRateMapper;
import com.ruoyi.datastatistics.domain.CopyRate;
import com.ruoyi.datastatistics.service.ICopyRateService;

/**
 * 抄表率Service业务层处理
 *
 * @author TsingYu
 * @date 2024-08-02
 */
@Service
public class CopyRateServiceImpl extends ServiceImpl<CopyRateMapper, CopyRate> implements ICopyRateService {
    private final CopyRateMapper copyRateMapper;

    public CopyRateServiceImpl(CopyRateMapper copyRateMapper) {
        this.copyRateMapper = copyRateMapper;
    }

    @Override
    public boolean addCopyDataByDate(String dateString, Integer terminalType) {
        if (StringUtils.isBlank(dateString)) {
            return false;
        }
        String[] datePeriods = dateString.split(",");
        Set<LocalDate> dateSet = new HashSet<>(datePeriods.length * 5);
        try {
            for (String datePeriod : datePeriods) {
                datePeriod = StringUtils.trim(datePeriod);
                if (StringUtils.contains(datePeriod, "~")) {
                    String begin = datePeriod.split("~")[0];
                    String end = datePeriod.split("~")[1];
                    dateSet.addAll(DateUtils.generateLocalDateListBetweenTwoDate(begin, end));
                } else {
                    dateSet.add(LocalDate.parse(datePeriod));
                }
            }
        } catch (Exception e) {
            return false;
        }
        List<String> orderedDateList = dateSet.stream().sorted().map(LocalDate::toString).collect(Collectors.toList());
        if (orderedDateList.size() > Month.JANUARY.maxLength()) {
            return false;
        }
        List<CopyRate> copyRates;
        if (terminalType == CopyRate.TERMINAL_TYPE_XB) {
            copyRates = copyRateMapper.selectXbCopyRateByDate(orderedDateList, CopyRate.TERMINAL_TYPE_XB);
        } else {
            copyRates = copyRateMapper.selectDbCopyRateByDate(orderedDateList, CopyRate.TERMINAL_TYPE_DB);
        }
        int batchSize = 500;
        List<List<CopyRate>> lists = CollectionUtil.split(copyRates, batchSize);
        for (List<CopyRate> list : lists) {
            list.forEach(e -> e.setCopyRate(e.getCopyCount() == null ? null : e.getTotalCount() == null || e.getTotalCount() == 0 ? null : BigDecimal.valueOf(e.getCopyCount()).divide(BigDecimal.valueOf(e.getTotalCount()), 4, RoundingMode.HALF_UP)));
            copyRateMapper.insertOrUpdateCopyRate(list);
        }
        return true;
    }
}
